﻿namespace Nomo.UnityCoreModule
{
    /// <summary>
    /// 选项卡组。
    /// </summary>
    [UnityEngine.DisallowMultipleComponent]
    public sealed class TabGroup : UnityEngine.EventSystems.UIBehaviour
    {
        private readonly System.Collections.Generic.List<Tab> _tabs = new System.Collections.Generic.List<Tab>();

        internal bool AnyTabsOn() => _tabs.Find(e => e != null && e.IsOn) != null;

        internal void NotifyTabOn(Tab tab)
        {
            if (tab == null)
            {
                throw new System.ArgumentNullException(nameof(tab));
            }
            if (!_tabs.Contains(tab))
            {
                throw new System.ArgumentException();
            }
            foreach (var element in _tabs)
            {
                if (element != tab)
                {
                    element.IsOn = false;
                }
            }
        }

        internal void RegisterTab(Tab tab)
        {
            if (_tabs.Contains(tab))
            {
                return;
            }
            _tabs.Add(tab);
        }

        internal void UnregisterTab(Tab tab)
        {
            if (!_tabs.Contains(tab))
            {
                return;
            }
            _tabs.Remove(tab);
        }

        internal void EnsureValidState()
        {
            if (AnyTabsOn() || _tabs.Count == 0)
            {
                return;
            }
            _tabs[0].IsOn = true;
            NotifyTabOn(_tabs[0]);
        }

        /// <inheritdoc />
        protected override void Start()
        {
            EnsureValidState();
            base.Start();
        }
    }
}
